var MaterialSettingDialog = function () {
  var template = /* html */ `
    <div class="material-setting-dialog" v-loading.fullscreen.lock="loading">
      <template v-if="isShow">
      <form-group group-title="整体设置" style="margin-bottom:10px">
        <div class="has-line">
          <el-form label-width="auto" size="small">
            <el-form-item label="每个分类高度">
              <el-input-number v-model="minHeight" :controls="false" :min="0" :precision="0" style="width:200px">
              </el-input-number>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="isGroup">按一级分类显示</el-checkbox>
            </el-form-item>
            <el-form-item label="一行分类个数">
              <el-input-number v-model="count" :controls="false" :min="1" :precision="0" style="width:200px">
              </el-input-number>
              <div class="el-form-item__error">注：该配置只在'按一级分类显示'的情况下有用</div>
            </el-form-item>
          </el-form>
        </div>
      </form-group>
      <form-group group-title="表格内容设置" style="margin-bottom:10px">
        <el-form label-width="auto" size="small">
          <el-form-item label="文本字号">
            <el-input-number v-model="fontSize" :controls="false" :min="12" :precision="0" style="width:200px">
            </el-input-number>
          </el-form-item>
          <el-form-item label="文本行高">
            <el-input-number v-model="lineHeight" :controls="false" :min="10" :precision="0" style="width:200px">
            </el-input-number>
          </el-form-item>
        </el-form>
      </form-group>
      <form-group group-title="分类显示设置" style="margin-bottom:10px">
        <div class="has-line">
          <div>注：当上面的'按一级分类显示'没有勾选时，会使用无分类的配置，并且必须有无分类配置</div>
          <div style="margin-top:5px" class="table-setting">
            <el-table fit border :data="classifyFieldList" style="width:100%" empty-text="暂无分类配置数据">
              <el-table-column label="分类" min-width="140px" header-align="center" key="classifyName">
                <template slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.classifyName" class="table-input">
                    <el-option v-for="item in classifyList" :key="item.value" :value="item.value" :label="item.label">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="配置内容" min-width="400px" header-align="center" key="columns">
                <template slot-scope="scope">
                  <check-group has-width :key="scope.row.id" :data="scope.row.columns" :size="6"></check-group>
                </template>
              </el-table-column>
              <el-table-column :resizable="false" label="操作" min-width="80px" align="center" key="handle">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="delClassifyConfig(scope.row)">删除</el-button>
                </template>
              </el-table-column>

              <template slot="append">
                <div class="add-row" :class="{'has-data':classifyFieldList.length>0}" :style="{width:tableWidth}"
                  @click="addClassifyConfig">
                  <i class="el-icon-plus"></i>
                  <span>新增分类配置</span>
                </div>
              </template>
            </el-table>
          </div>
        </div>
      </form-group>

      <div style="text-align:center;margin-bottom:10px">
        <el-button size="medium" type="primary" @click="ensure">保存</el-button>
      </div>
      </template>
    </div>
  `;

  return {
    props: {
      config: {
        type: Object,
        required: true
      }
    },

    data: function () {
      var material = this.config.material;
      return {
        isShow: false,
        minHeight: material.minHeight,
        isGroup: material.isGroup,
        count: material.count,
        fontSize: material.fontSize,
        lineHeight: material.lineHeight,
        classifyList: [],
        classifyFieldList: [],
        tableWidth: '100%'
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.setClassifyList().then(function () {
        self.setClassifyFieldList();
        self.loading = false;
        self.isShow = true;
        self.tableWidthEvent();
      }).catch(function () {
        self.loading = false;
        self.isShow = true;
      });
    },

    methods: {
      setClassifyList: function () {
        var self = this;
        return ajaxRequest('createOrderForBomOrder/getLevelRankList', {
          status: 1
        }).then(function (res) {
          var classifyList = res.returnData;
          var classifys = [{
            value: "noClassify",
            label: "无分类"
          }];

          for (var i = 0; i < classifyList.length; i++) {
            var classify = classifyList[i];
            var levelRankOne = classify.levelRankOne;
            if (!SysUtil.isEmpty(levelRankOne)) {
              classifys.push({
                value: levelRankOne,
                label: levelRankOne
              })
            }
          }
          classifys = _.uniqBy(classifys, 'value');
          self.classifyList = classifys;
          return classifys;
        });
      },

      setClassifyFieldList: function () {
        var material = this.config.material;
        var classifyList = material.classifyConfig;
        var classifyFieldList = [];
        var materialFields = MaterialColorConfigModel.materialFields;
        for (var i = 0; i < classifyList.length; i++) {
          var classify = classifyList[i];
          var columns = classify.columns;
          var columnGroup = _.groupBy(columns, 'id');
          var columnList = [];
          for (var j = 0; j < materialFields.length; j++) {
            var fieldObj = materialFields[j];
            var id = fieldObj.id;
            var columnObj = columnGroup[id];
            if (columnObj === undefined) {
              columnObj = {
                id: id,
                checked: false,
                width: undefined
              };
            } else {
              columnObj = _.cloneDeep(columnObj[0]);
              if (columnObj.width === undefined) {
                columnObj.width = undefined;
              }
              columnObj.checked = columnObj.isShow;
              delete columnObj.isShow;
            }
            columnObj.label = fieldObj.label;
            columnList.push(columnObj);
          }

          classifyFieldList.push({
            id: SysUtil.getId(),
            classifyName: classify.classifyName,
            columns: columnList
          });
        }
        this.classifyFieldList = classifyFieldList;
      },

      addClassifyConfig: function () {
        var classifyFieldList = this.classifyFieldList;
        var materialFields = MaterialColorConfigModel.materialFields;
        var columns = [];
        for (var i = 0; i < materialFields.length; i++) {
          var obj = materialFields[i];
          columns.push({
            id: obj.id,
            label: obj.label,
            checked: false,
            width: undefined
          });
        }
        classifyFieldList.push({
          id: SysUtil.getId(),
          classifyName: '',
          columns: columns
        });
      },

      delClassifyConfig: function (classify) {
        var classifyFieldList = this.classifyFieldList;
        var index = _.findIndex(classifyFieldList, {
          id: classify.id
        });
        if (index > -1) {
          classifyFieldList.splice(index, 1);
        }
      },

      tableWidthEvent: function () {
        var self = this;
        this.$nextTick(function () {
          var $tableDiv = $(this.$el).find('.table-setting');
          var $table = $tableDiv.find('.el-table__header-wrapper table');
          $table.resize(function () {
            self.setTableWidth($table);
          });
          self.setTableWidth($table);
        });
      },

      setTableWidth: function ($table) {
        var self = this;
        this.$nextTick(function () {
          var tableWidth = $table.width();
          if (tableWidth === null) {
            return;
          }
          self.tableWidth = tableWidth + 'px';
        });
      },

      ensure: function () {
        if (!this.checkValid()) {
          return;
        }

        var material = this.config.material;
        material.resetData({
          minHeight: this.minHeight,
          isGroup: this.isGroup,
          count: this.count,
          fontSize: this.fontSize,
          lineHeight: this.lineHeight,
          classifyConfig: this.classifyFieldList
        });
        this.$emit('setting-success');
      },

      checkValid: function () {
        var minHeight = this.minHeight;
        if (minHeight === undefined) {
          this.$alert('请输入每个分类高度', '信息');
          return false;
        }

        if (this.isGroup) {
          if (this.count === undefined) {
            this.$alert('请输入一行分类个数', '信息');
            return false;
          }
        }

        var fontSize = this.fontSize;
        if (fontSize === undefined) {
          this.$alert('请输入文本字号', '信息');
          return false;
        }

        var lineHeight = this.lineHeight;
        if (lineHeight === undefined) {
          this.$alert('请输入文本行高', '信息');
          return false;
        }

        var classifyFieldList = this.classifyFieldList;
        if (classifyFieldList.length === 0) {
          this.$alert('请设置分类显示');
          return false;
        }

        var classifyNames = [];
        for (var i = 0; i < classifyFieldList.length; i++) {
          var fieldObj = classifyFieldList[i];
          var classifyName = fieldObj.classifyName;
          if (classifyName === '') {
            this.$alert(`分类显示设置中，第${i+1}行未设置分类`);
            return false;
          }

          var columns = fieldObj.columns;
          columns = _.filter(columns, {
            checked: true
          });
          if (columns.length === 0) {
            var msg = `分类显示设置中，分类'${classifyName==='noClassify'?'无分类':classifyName}'未设置显示列`;
            this.$alert(msg);
            return false;
          }

          for (var j = 0; j < columns.length; j++) {
            var columnObj = columns[j];
            if (columnObj.width === undefined) {
              var msg = `分类显示设置中，分类'${classifyName==='noClassify'?'无分类':classifyName}'的'${columnObj.label}'列未设置宽度`;
              this.$alert(msg);
              return false;
            }
          }
          classifyNames.push(classifyName);
        }

        var list = _.uniq(classifyNames);
        if (list.length !== classifyNames.length) {
          this.$alert('分类显示设置中，设置的分类有重复');
          return false;
        }

        if (!this.isGroup) {
          if (classifyNames.indexOf('noClassify') === -1) {
            this.$alert(`当物料不按一级分类显示时，分类显示中必须设置'无分类'的显示列`);
            return false;
          }
        }
        return true;
      }
    },

    components: {
      FormGroup: FormGroup,
      CheckGroup: CheckGroup
    },

    template: template
  };
}();
